package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;

/**
 * @author lo
 * @date 2021/9/28
 */
@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    // 指定MinIo实现
    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;

    @Autowired
    Configuration configuration;

    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Value("${file.minio.prefix}")
    String prefix;

    /**
     * 静态化页面
     *
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //1.获取模板对象
            Template template = configuration.getTemplate("article.ftl");
            HashMap<String, Object> map = new HashMap<>(8);

            //2.模板需要三个数据 文章数据,文章内容,作者id
            map.put("article", apArticle);
            map.put("content", JSONArray.parseArray(content));
            //获取用户id
            ApAuthor author = authorMapper.selectById(apArticle.getAuthorId());
            Integer userId = author.getUserId();
            map.put("authorApUserId", userId);
            //3.获取字符输出流
            StringWriter writer = new StringWriter();
            //4.将数据和模板合成
            template.process(map, writer);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            //5.将静态网页输出到服务器中
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            System.out.println("测试路径 = " + path);
            apArticle.setStaticUrl(path);
            //6.更新article状态
            apArticleMapper.updateById(apArticle);
            log.debug("页面静态化完成,文章路径: {},文章id:{}", path, apArticle.getId());
        } catch (IOException e) {
            e.printStackTrace();
            log.debug("页面静态化失败,文章id: {},失败原因:{}",apArticle.getId(),e.getCause());
        } catch (TemplateException e) {
            e.printStackTrace();
            log.debug("页面静态化失败,文章id: {},失败原因:{}",apArticle.getId(),e.getCause());
        }


    }
}
